package com.lge.qcontact.configuration;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import com.lge.qcontact.MainActivity;
import com.lge.qcontact.R;
import com.lge.qcontact.utils.LocalDBHelper;
import com.lge.qcontact.utils.MUtils;

public class FixGroupActivity extends Activity {
	private ArrayList<String> spinnerList;
	private ArrayList<String> groupList;

	private Spinner grpSpinner;
	private Button btnFixGrouop;
	private EditText gNameField;
	private ArrayAdapter<String> sAdapter;

	private SQLiteDatabase localDB;

	private String isMaster="true";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_fix_group);
		
		spinnerList = new ArrayList<String>();
		groupList = new ArrayList<String>();
		
		localDB = (new LocalDBHelper(getBaseContext())).getWritableDatabase();
		Cursor c = localDB.rawQuery(
				"select gname from CONTACTS group by gname", null);

		while (c.moveToNext()) {
			groupList.add(c.getString(0));
		}
		//localDB.close();
		c.close();

		spinnerList.add("선택해 주세요.");
		spinnerList.add("그룹 추가");
		for (String gName : groupList) {
			spinnerList.add(gName);
		}

		gNameField = (EditText) findViewById(R.id.fixGroupNameField);
		grpSpinner = (Spinner) findViewById(R.id.spinnerGroups);

		btnFixGrouop = (Button) findViewById(R.id.fixGroupBtn);
		btnFixGrouop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (btnFixGrouop.getText().toString().equals("그룹 변경")) {
					btnFixGrouop.setError("spinner 아이템을 선택해주세요.");
				} else if (btnFixGrouop.getText().toString().equals("그룹 삭제")) {
					String gname = gNameField.getText().toString();
					Cursor c1 = localDB.rawQuery("select uid from LOGIN_INFO", null);
					c1.moveToNext();
					String userId = c1.getString(0);
					
					Cursor c = localDB.rawQuery("select isMaster from CONTACTS where gname='"+gname+"' and uid='"+ userId +"';", null);
					c.moveToNext();
					MUtils.loge("ismaster = " + gname + c.getString(0));
					if(c.getString(0).equals("true")){
						AlertDialog.Builder builder = new AlertDialog.Builder(FixGroupActivity.this);
						builder.setTitle("주의!");
						builder.setMessage("당신은 "+gname+" 그룹의 MASTER입니다. " +
													 "삭제하시면 모든 그룹원에 대한 데이터가 삭제됩니다.\n" +
													 "\n 삭제 하시겠습니까?");
						builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								localDB.execSQL("delete from CONTACTS where gname='"
										+ gNameField.getText().toString() + "';");
								DeleteMasterThread t = new DeleteMasterThread();
								t.start();
								try {
									t.join();
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
								
								
								MUtils.toast(getBaseContext(), "삭제가 완료되었습니다.");
							
								finish();
							}
						});
						builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								
							}
						});
						builder.show();
					}else{
						localDB.execSQL("delete from CONTACTS where gname='"
								+ gNameField.getText().toString() + "';");
						DeleteThread t = new DeleteThread();
						t.start();
						try {
							t.join();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						
						
						MUtils.toast(getBaseContext(), "삭제가 완료되었습니다.");
					
						finish();
					}
					
					
				} else if (btnFixGrouop.getText().toString().equals("그룹 추가")) {
					for(String group : spinnerList){
						if(group.equals(gNameField.getText().toString())){
							gNameField.setError("이미 등록된 그룹입니다.");
							return;
						}
						
					}
					
					SearchGroupThread t1 = new SearchGroupThread();
					t1.start();
					try {
						t1.join();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					
					RegistThread t = new RegistThread();
					t.start();
					try {
						t.join();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					MUtils.toast(getBaseContext(), "등록이 완료되었습니다.");
					
					finish();
				}
			}
		});

		sAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, spinnerList);
		sAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		grpSpinner.setAdapter(sAdapter);

		grpSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				if (position == 0) {
					btnFixGrouop.setText("그룹 변경");
				} else if (position == 1) {
					
					gNameField.setEnabled(true);
					btnFixGrouop.setText("그룹 추가");
				} else {
					gNameField.setText(groupList.get(position - 2));
					btnFixGrouop.setText("그룹 삭제");
				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}

		});

	}

	class DeleteThread extends Thread {

		@Override
		public void run() {
			Cursor c = localDB.rawQuery("select uid from LOGIN_INFO", null);
			c.moveToNext();
			String userId = c.getString(0);

			StringBuffer sql = new StringBuffer(
					"http://192.168.0.205:8080/com.lg.project.myexample.cmd.DeleteGroupCmd.vcc?param="
							+ gNameField.getText().toString() + "," + userId);

			try {
				URL url = new URL(sql.toString());
				url.openStream();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	class DeleteMasterThread extends Thread {

		@Override
		public void run() {

			StringBuffer sql = new StringBuffer(
					"http://192.168.0.205:8080/com.lg.project.myexample.cmd.DeleteGroupMasterCmd.vcc?param="
							+ gNameField.getText().toString());

			try {
				URL url = new URL(sql.toString());
				url.openStream();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	class RegistThread extends Thread {

		@Override
		public void run() {

			Cursor c = localDB
					.rawQuery("select uid, upw from LOGIN_INFO", null);
			c.moveToNext();
			String userId = c.getString(0);
			
			
			c = localDB.rawQuery(
					"select uName, phoneNo, mobile, email from CONTACTS where uid='"
							+ userId + "';", null);
			c.moveToNext();

			String uName = c.getString(0);
			String phoneNo = c.getString(1);
			String mobile = c.getString(2);
			String email = c.getString(3);


			StringBuffer sql = new StringBuffer(
					"http://192.168.0.205:8080/com.lg.project.myexample.cmd.RegGroupCmd.vcc?param=");

			sql.append(userId+",").append(email+",").append(mobile+",").append(phoneNo+",")
			.append(gNameField.getText().toString()+",").append(isMaster);
					
			MUtils.loge("sql : " + sql.toString() + " " + isMaster);
			try {
				URL url = new URL(sql.toString());
				url.openStream();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	class SearchGroupThread extends Thread {
		
		String tag = null;

		public SearchGroupThread() {}

		public void run() {
			
			try {
				URL url = new URL(
						"http://192.168.0.205:8080/com.lg.project.myexample.cmd.GroupSearchCmd.vcc?param="
								+ gNameField.getText().toString());
				
				

				XmlPullParserFactory factory = XmlPullParserFactory
						.newInstance();
				XmlPullParser parser = factory.newPullParser();
				parser.setInput(url.openStream(), "utf-8");
			

				int eventType = parser.getEventType();
				while (eventType != XmlPullParser.END_DOCUMENT) {
					switch (eventType) {
					case XmlPullParser.START_DOCUMENT:
						break;
					case XmlPullParser.START_TAG:
						if (parser.getName().equals("gname")) {
							isMaster = "false";
						}
						
						
						break;
					case XmlPullParser.END_TAG:
						break;
					}
					eventType = parser.next();
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		localDB.close();
	}
}
